const CN_UPPER_NUMBER: string[] = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
const CN_UPPER_MONETRAY_UNIT: string[] = ['圆', '拾', '佰', '仟', '万', '拾', '佰', '仟', '亿', '拾', '佰', '仟', '兆']
const CN_UPPER_MONETRAY_UNIT_BASE: string[] = ['圆', '万', '亿', '兆']

const ZREO: string = '零'
const CN_FULL: string = '整'
const CN_ZREO_FULL: string = '零圆整'

export function moneyToUpper(money: number): string {
  if (money < 0) {
    alert('金额不能为负数')
    return ''
  } else if (!/^[0-9]+([.][0-9]{1,2})?$/.test(String(money))) {
    alert('数值类型错误，必须是整数或1-2位小数')
    return ''
  } else {
    // 特殊值：0
    if (money == 0) {
      return CN_ZREO_FULL
    }

    console.log('金额' + money)
    let decimal: number = parseInt(((money * 100) % 100).toFixed(0))
    let integer: number = (money * 100 - ((money * 100) % 100)) / 100
    console.log('整数部分' + integer)
    console.log('小数部分' + decimal)

    // 整数部分和小数部分分开处理
    if (decimal == 0) {
      return integerToUpperMoney(money).concat(CN_FULL)
    } else {
      let buffer: string = ''
      // 整数部分
      buffer = integerToUpperMoney(integer)
      // 小数部分
      if (decimal == 0) {
        buffer = buffer.concat(CN_FULL)
      } else if (decimal < 10) {
        buffer = buffer
          .concat(ZREO)
          .concat(CN_UPPER_NUMBER[decimal])
          .concat('分')
      } else {
        buffer = buffer.concat(CN_UPPER_NUMBER[(decimal - (decimal % 10)) / 10]).concat('角')
        if (decimal % 10 > 0) {
          buffer = buffer.concat(CN_UPPER_NUMBER[decimal % 10]).concat('分')
        }
      }

      return buffer
    }
  }
}

function integerToUpperMoney(integer: number): string {
  let buffer: string = ''
  let index: number = 0
  if (integer == 0) {
    buffer = buffer.concat(ZREO).concat(CN_UPPER_MONETRAY_UNIT[index])
  }
  while (integer > 0) {
    let i = integer % 10

    if (i == 0) {
      if (index == 0 || index == 4 || index == 8) {
        buffer = CN_UPPER_MONETRAY_UNIT[index++].concat(buffer)
      } else {
        if (buffer.substring(0, 1) != ZREO && CN_UPPER_MONETRAY_UNIT_BASE.indexOf(buffer.substring(0, 1)) < 0) {
          buffer = ZREO.concat(buffer)
        }
        index++
      }
    } else {
      buffer = CN_UPPER_MONETRAY_UNIT[index++].concat(buffer)
      buffer = CN_UPPER_NUMBER[i].concat(buffer)
    }

    integer = (integer - i) / 10
  }
  return buffer
}
